import mongoose, { Document, Schema } from 'mongoose'

export interface IRankingHistory extends Document {
  type: 'gift' | 'popularity'
  roomId?: mongoose.Types.ObjectId
  rankings: Array<{
    rank: number
    userId?: mongoose.Types.ObjectId
    roomId?: mongoose.Types.ObjectId
    score: number
  }>
  period: 'daily' | 'weekly' | 'monthly'
  startTime: Date
  endTime: Date
  createdAt: Date
}

const RankingHistorySchema = new Schema({
  type: {
    type: String,
    enum: ['gift', 'popularity'],
    required: true,
  },
  roomId: {
    type: Schema.Types.ObjectId,
    ref: 'Room',
  },
  rankings: [
    {
      rank: Number,
      userId: {
        type: Schema.Types.ObjectId,
        ref: 'User',
      },
      roomId: {
        type: Schema.Types.ObjectId,
        ref: 'Room',
      },
      score: Number,
    },
  ],
  period: {
    type: String,
    enum: ['daily', 'weekly', 'monthly'],
    required: true,
  },
  startTime: {
    type: Date,
    required: true,
  },
  endTime: {
    type: Date,
    required: true,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
})

// 创建索引
RankingHistorySchema.index({ type: 1, period: 1, startTime: -1 })
RankingHistorySchema.index({ roomId: 1, type: 1, period: 1 })

export const RankingHistory = mongoose.model<IRankingHistory>(
  'RankingHistory',
  RankingHistorySchema
)
